import React, { useState } from 'react';
import { Table, Pagination, Card, Tag, Button } from 'antd';
import moment from 'moment';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import Search from './Search';
import Detail from './Detail';
import { getQualityTag, getHour, toVersionReleaseFlag } from '../utils';
import { useVersionList } from '../hooks';
import styles from './index.less';

// 筛选数组
const filtersReleaseFlag = [
    {
        text: '上线',
        value: '0'
    },
    {
        text: '研发中',
        value: '1'
    },
    {
        text: '测试中',
        value: '2'
    }
];
const filtersMap = {
    releaseFlag: filtersReleaseFlag
};

const Version = ({ location }) => {
    const [detailVisible, setDetailVisible] = useState(false); // 控制弹窗显示
    const [detailId, setDetailId] = useState(null); // 弹窗数据

    const { query } = location;
    // 维护参数
    const [params, setParams] = useState({
        pageNo: query.pageNo || 1,
        pageSize: query.pageSize || 10,
        total: query.total || 10,
        versionStartDate: query.versionStartDate || null,
        versionEndDate: query.versionEndDate || null,
        releaseFlag: query.releaseFlag || null
    });
    const [listLoading, listData, listTotal] = useVersionList(params);

    // 筛选默认值
    const getFilterValue = field => {
        const list = filtersMap[field];
        const value = params[field];
        const exist = list.find(item => item.value === value);
        if (exist) {
            return [exist.value];
        }
        return [];
    };

    const columns = [
        {
            title: '版本',
            dataIndex: 'versionNo',
            key: 'versionNo',
            render: (text, record) => (
                <Button
                    type="link"
                    style={{ padding: 0 }}
                    onClick={() => {
                        // 显示模态框
                        setDetailId(record.id);
                        setDetailVisible(true);
                    }}
                >
                    {text}
                </Button>
            )
        },
        {
            title: '版本标题',
            dataIndex: 'versionName',
            key: 'versionName',
            width: 200
        },
        {
            title: '版本状态',
            dataIndex: 'status',
            key: 'status',
            filters: filtersReleaseFlag,
            filterMultiple: false,
            filteredValue: getFilterValue('releaseFlag'),
            render: (data, record) => (
                <>
                    <span style={{ marginRight: 5 }}>{toVersionReleaseFlag(record.releaseFlag)}</span>
                    {data === '0' && <span className={styles.normalTag}>正常</span>}
                    {data === '1' && <span className={styles.InsTag}>逾期</span>}
                </>
            )
        },
        {
            title: '排期',
            dataIndex: 'versionStartDate',
            key: 'versionStartDate',
            width: 200,
            render: (data, record) => (
                <>
                    {data && moment(data).format('YYYY.MM.DD')} -
                    {record.versionEndDate && moment(record.versionEndDate).format('YYYY.MM.DD')}
                </>
            )
        },
        {
            title: '产品线',
            dataIndex: 'productName',
            key: 'productName'
        },
        {
            title: '项目组',
            dataIndex: 'projectGroupName',
            key: 'projectGroupName'
        },
        {
            title: '任务数',
            dataIndex: 'normalDoingTaskNum',
            key: 'normalDoingTaskNum',
            render: (data, record) => {
                const count =
                    record.overdueTaskNum && record.overdueWarnTaskNum
                        ? record.overdueTaskNum + record.overdueWarnTaskNum
                        : 0;
                return (
                    <>
                        {data ||
                            0 + record.normalDoneTaskNum ||
                            0 + record.overdueDoneTaskNum ||
                            0 + record.overdueTaskNum ||
                            0 + record.overdueWarnTaskNum ||
                            0}
                        {count === 0 ? (
                            <span style={{ color: '#555' }}>（无逾期）</span>
                        ) : (
                            <span style={{ color: '#A30014' }}>（逾期{count}）</span>
                        )}
                    </>
                );
            }
        },
        {
            title: '任务质量',
            dataIndex: 'evalScore',
            key: 'evalScore',
            render: (data, record) => {
                const rt = getQualityTag(record.evalRank);
                return (
                    <>
                        <span style={{ marginRight: 5 }}>{(data && data.toFixed(2)) || '--'}</span>
                        {record.evalRank && <Tag color={rt.color}>{rt.label}</Tag>}
                    </>
                );
            }
        },
        {
            title: '工作量（计划/额定/已完成）',
            dataIndex: 'planWorkloadNum',
            key: 'planWorkloadNum',
            align: 'center',
            render: (data, record) => (
                <>
                    {getHour(data)} / {getHour(record.shouldDoneWorkloadNum)} / {getHour(record.actualDoneWorkloadNum)}
                    小时
                </>
            )
        },
        {
            title: '人均Bug量',
            dataIndex: 'perCapitaBugNum',
            key: 'perCapitaBugNum',
            align: 'center',
            render: data => data || '--'
        }
    ];

    // 搜索查询
    const handleSearch = obj => {
        setParams({ ...params, ...obj, pageNo: 1 });
    };

    /* 翻页 */
    const handlePageNoChange = React.useCallback(
        pageNo => {
            setParams({ ...params, pageNo });
        },
        [params]
    );

    const handlePageSizeChange = React.useCallback(
        (_, pageSize) => {
            setParams({ ...params, pageSize, pageNo: 1 });
        },
        [params]
    );

    // 表格操作
    const onChangeTable = (pagination, filters) => {
        const extraQuery = {};
        if (filters && Object.keys(filters).length) {
            Object.keys(filters).forEach(item => {
                const [filterValue] = filters[item];
                if (item === 'status') {
                    extraQuery.releaseFlag = filterValue;
                } else {
                    extraQuery[item] = filterValue;
                }
            });
        }
        setParams({ ...params, ...extraQuery });
    };

    return (
        <PageHeaderWrapper>
            <Card>
                <div style={{ marginBottom: 24 }}>
                    <Search query={params} onSearch={handleSearch} />
                </div>
                <Table
                    rowKey={(record, index) => index}
                    columns={columns}
                    dataSource={listData}
                    onChange={onChangeTable}
                    pagination={false}
                    loading={listLoading}
                    scroll={{ x: 'max-content' }}
                />
                <div style={{ display: 'flex', justifyContent: 'flex-end', marginTop: 24 }}>
                    {listTotal > 0 ? (
                        <Pagination
                            showTotal={total => `总共 ${total} 条`}
                            showSizeChanger
                            showQuickJumper
                            loading={listLoading}
                            total={listTotal}
                            current={Number(params.pageNo)}
                            pageSize={Number(params.pageSize)}
                            onChange={handlePageNoChange}
                            onShowSizeChange={handlePageSizeChange}
                        />
                    ) : null}
                </div>
            </Card>
            {detailId && (
                <Detail
                    visible={detailVisible}
                    id={detailId}
                    onClose={() => {
                        setDetailVisible(false);
                    }}
                />
            )}
        </PageHeaderWrapper>
    );
};

export default Version;
